const redis = require('redis')
const client = redis.createClient(6379,'127.0.0.1')

//连接错误处理
client.on("error", err => {
    console.log('redis connect err', err);
});

client.on('connect', () => {
    console.log('redis connect success');
})

//验证redis
// client.auth(config.password);

let redisHelper = {};

/**
 * redisHelper setString function
 * @param key
 * @param value
 * @param expire
 */
redisHelper.setString = (key, value, expire) => {
    return new Promise((resolve, reject) => {
        client.set(key, value, function (err, result) {

            if (err) {
                console.log(err);
                reject(err);
            }

            if (!isNaN(expire) && expire > 0) {
                client.expire(key, parseInt(expire));
            }
            resolve(result)
        })
    })
}

// 异步获取redis的值
redisHelper.getString = async(key) => {
    const newGet = async(key) => {
        let val = await new Promise((resolve => {
            client.get(key, function (err, res) {
                return resolve(res);
            });
        }));
        return JSON.parse(val);
    };
    return await newGet(key);
};

module.exports = redisHelper;